package com.dhcc.core.modules.msgcenter.push;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.msgcenter.constant.MsgReceiveType;
import com.dhcc.core.modules.msgcenter.entity.Msg;
import com.dhcc.core.modules.msgcenter.service.IMsgService;
import com.dhcc.core.modules.msgcenter.vo.MsgPush;
import com.dhcc.core.modules.system.entity.User;

/**
 * 发送系统消息
 */
@Service("sysMsgPushService")
public class SysMsgPushService extends AbsPushService {

    private final static Logger logger = LoggerFactory.getLogger(SysMsgPushService.class);
    @Autowired
    private IMsgService msgService;

    @Override
    public void send(MsgPush msgPush, String pushType) {
        if (msgPush.getReceiveType() == MsgReceiveType.ALL.getCode()) {
            Msg msg = new Msg();
            msg.setDatas(msgPush.getDatas());
            msg.setModuleId(msgPush.getModuleId());
            msg.setModuleName(msgPush.getModuleName());
            msg.setMsgContent(msgPush.getMsgContentByTpl());
            msg.setMsgTitle(msgPush.getMsgTitle());
            msg.setReceiveType(MsgReceiveType.ALL.getCode());
            msg.setSendTime(new Date());
            msg.setSendUserId(msgPush.getSendUserId());
            msg.setSendUserName(msgPush.getSendUserName());
            msg.insert();
        } else {
            List<User> receiveUsers = this.getReceiveUsers(msgPush, pushType);
            if (CommonUtil.isNotEmpty(receiveUsers)) {
                List<Msg> msgs = new ArrayList<>();
                for (User user : receiveUsers) {
                    Msg msg = new Msg();
                    msg.setDatas(msgPush.getDatas());
                    msg.setModuleId(msgPush.getModuleId());
                    msg.setModuleName(msgPush.getModuleName());
                    msg.setMsgContent(msgPush.getMsgContentByTpl());
                    msg.setMsgTitle(msgPush.getMsgTitle());
                    msg.setReceiveType(MsgReceiveType.USER.getCode());
                    msg.setReceiveId(user.getId());
                    msg.setReceiveName(user.getName());
                    msg.setSendTime(new Date());
                    msg.setSendUserId(msgPush.getSendUserId());
                    msg.setSendUserName(msgPush.getSendUserName());
                    msgs.add(msg);
                }
                msgService.insertBatch(msgs);
            }
        }
        logger.debug("系统消息发送成功...");
    }
}